package com.lagou.server.handler;

import com.lagou.server.service.entity.RpcRequest;
import com.lagou.server.utiz.SpringUtils;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Map;

@Component
@ChannelHandler.Sharable
public class UserServerHandler extends ChannelInboundHandlerAdapter {


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        // 判断是否符合约定，符合则调用本地方法，返回数据
        // msg:  UserService#sayHello#are you ok?
//        if(msg.toString().startsWith("UserService")){
//            UserServiceImpl userService = new UserServiceImpl();
//            String result = userService.sayHello(msg.toString().substring(msg.toString().lastIndexOf("#") + 1));
//            ctx.writeAndFlush(result);
//        }

        if(msg instanceof RpcRequest){
            RpcRequest rpcRequest = (RpcRequest) msg;

            System.out.println(rpcRequest);

            String className = rpcRequest.getClassName();
            String methodName = rpcRequest.getMethodName();
            Class<?>[] parameterTypes = rpcRequest.getParameterTypes();
            Object[] parameters = rpcRequest.getParameters();

            Class<?> serviceClass = Class.forName(className);
            Map<String, ?> beansOfType = SpringUtils.getBeansOfType(serviceClass);

            if(beansOfType != null){
                Collection<?> values = beansOfType.values();
                if(values.size() > 0){
                    for(Object obj: values){

                        Method method = obj.getClass().getMethod(methodName, parameterTypes);
                        Object result = method.invoke(obj, parameters);
                        ctx.writeAndFlush(result);
                        break;
                    }
                }
            }
        }
    }
}
